package com.platform.qujia.service.impl;

import com.platform.qujia.constantEnum.DecimalConstant;
import com.platform.qujia.controller.QuJiaPayV2Controller;
import com.platform.qujia.dao.FleetCardMapper;
import com.platform.qujia.dao.FleetCardSubMapper;
import com.platform.qujia.dao.PayOrderMapper;
import com.platform.qujia.enums.ElectronCardType;
import com.platform.qujia.enums.PayTypeEnum;
import com.platform.qujia.handle.PayOrderHandle;
import com.platform.qujia.param.request.PayOrderRequest;
import com.platform.qujia.pojo.*;
import com.platform.qujia.pojo.dto.ReductionAndCouponDTO;
import com.platform.qujia.pojo.vo.PayOrderVO;
import com.platform.qujia.pojo.vo.StoredCardVO;
import com.platform.qujia.service.*;
import com.platform.qujia.utils.*;
import com.platform.qujia.utils.CodeMsg;
import com.platform.qujia.utils.MathUtil;
import com.platform.qujia.utils.exception.CustomException;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * @date 2023/10/16
 */
@NoArgsConstructor
@Data
@Service
public class AppUserOrderServiceImpl implements AppUserOrderService {

    private static final Logger log = LoggerFactory.getLogger(AppUserOrderServiceImpl.class);

    @Autowired
    private PayOrderMapper payOrderMapper;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private AppUserInfoService appUserInfoService;
    @Autowired
    private ElectronicMembershipCardService electronicMembershipCardService;
    @Autowired
    private ReductionActivityService reductionActivityService;

    @Resource
    private PayOrderService payOrderService;
    @Autowired
    private FleetCardSubMapper fleetCardSubMapper;
    @Autowired
    private FleetCardMapper fleetCardMapper;
    @Autowired
    private QuJiaPayV2Controller quJiaPayV2Controller;
    @Autowired
    private FleetCardService fleetCardService;
    @Autowired
    private FleetCardSubService fleetCardSubService;
    @Autowired
    private GzhNewsTemplateService gzhNewsTemplateService;
    @Autowired
    private CustomerCardSettingService customerCardSettingService;

    @Override
    @Transactional
    public PayOrderVO createOrder(PayOrderRequest request) {
        log.info("AppUser-CreateOrder====request:[{}]", request.toString());
        return saveOrUpdatePayOrder(null,request);

    }

    @Override
    @Transactional
    public PayOrderVO updateOrder(PayOrderRequest request) {
        log.info("AppUser-UpdateOrder====request:[{}]", request.toString());
        PayOrder payOrder = queryNotPaidOrderByOrderNo(request.getOrderNo());
        payOrder.setPayType(request.getPayType());
        return saveOrUpdatePayOrder(payOrder,request);
    }

    @Override
    @Transactional
    public void pay(PayOrderRequest request) {
        log.info("AppUser-pay====request:[{}]", request.getOrderNo());
        PayOrder payOrder = queryNotPaidOrderByOrderNo(request.getOrderNo());
        String payType = request.getPayType();
        switch (payType){
            case "tyk":
            case "dzk":
                dzkPay(payOrder,request.getCouponUserId(),request.getPassword(),"dzk_ht",StringUtils.equals("tyk",payType));
                break;
            case "cdk":
                fleetPay(payOrder,request);
                break;
            default:
                throw new CustomException("不支持该支付方式");
        }
    }

    @Override
    public List<StoredCardVO> queryStoredCardVOList(PayOrderRequest request) {
        Station station = enterpriseService.selectStationById(request.getStationId());
        if(station == null){
            throw new CustomException("未查询到油站");
        }
        AppUserInfo userInfo = queryAppUserInfo(request.getConsumerId());
        StaOilGun staOilGun = queryStaOilGun(request.getGunName(), station.getStationId());
        ArrayList<StoredCardVO> cardVOS = new ArrayList<>();
        CustomerCardSetting query = new CustomerCardSetting();
        query.setEnterpriseId(station.getEnterpriseId());
        CustomerCardSetting setting = customerCardSettingService.getOneJoinEnterprise(query);
        if (StringUtils.equals("1",setting.getCardEnabledFlag())) {
            CustomerElectronicCard card = queryElectronicCard(userInfo, staOilGun.getOil().getCardType(), station);
            StoredCardVO dzk = new StoredCardVO();
            dzk.setAmt(card == null ? BigDecimal.ZERO : card.getTotalAmt());
            dzk.setStoredCardType(PayTypeEnum.dzk.getType());
            dzk.setStoredCardName(PayTypeEnum.dzk.getDes());
            cardVOS.add(dzk);

            if (StringUtils.contains(setting.getCardOilsType(),ElectronCardType.GENERIC.getKey())) {
                CustomerElectronicCard tyCard = queryElectronicCard(userInfo, ElectronCardType.GENERIC.getKey(), station);
                StoredCardVO tyk = new StoredCardVO();
                tyk.setAmt(tyCard == null ? BigDecimal.ZERO : tyCard.getTotalAmt());
                tyk.setStoredCardType("tyk");
                tyk.setStoredCardName("通用卡");
                cardVOS.add(tyk);
            }
//            else{
//                StoredCardVO tyk = new StoredCardVO();
//                tyk.setAmt(BigDecimal.ZERO);
//                tyk.setStoredCardType("tyk");
//                tyk.setStoredCardName("通用卡");
//                cardVOS.add(tyk);
//            }
        }else{
            StoredCardVO dzk = new StoredCardVO();
            dzk.setAmt(BigDecimal.ZERO);
            dzk.setStoredCardType(PayTypeEnum.dzk.getType());
            dzk.setStoredCardName(PayTypeEnum.dzk.getDes());
            cardVOS.add(dzk);
//            StoredCardVO tyk = new StoredCardVO();
//            tyk.setAmt(BigDecimal.ZERO);
//            tyk.setStoredCardType("tyk");
//            tyk.setStoredCardName("通用卡");
//            cardVOS.add(tyk);
        }

//        FleetCardSubVo cardSubVo = queryFleetCard(userInfo, Long.valueOf(station.getEnterpriseId()));
//        StoredCardVO cdk = new StoredCardVO();
//        cdk.setAmt(cardSubVo == null ? BigDecimal.ZERO : cardSubVo.getBalance());
//        cdk.setStoredCardType(PayTypeEnum.cdk.getType());
//        cdk.setStoredCardName(PayTypeEnum.cdk.getDes());
//        cardVOS.add(cdk);

        return cardVOS;
    }

    private void dzkPay(PayOrder payOrder,String couponUserId,String password,String payType,boolean genericPay){
        AppUserInfo userInfo = queryAppUserInfo(payOrder.getConsumerId());
        if (StringUtils.equals("1",userInfo.getIsFree())) {
            if (StringUtils.isBlank(password)) {
                throw new CustomException("请输入支付密码");
            }
            String inputPassword = DESUtils.encrypt(password);
            if(!inputPassword.equals(userInfo.getPayPassword())){
                throw new CustomException("支付密码错误");
            }
        }
        ResultData payRes = quJiaPayV2Controller.newDzkCouponPaySetV3(payOrder.getOrderNo(), couponUserId,payType,genericPay);
        int retCode = payRes.getRetCode();
        if(retCode!=0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new CustomException(payRes.getMessage(),payRes.getRetCode());
        }
    }

    private void fleetPay(PayOrder payOrder, PayOrderRequest request){
        AppUserInfo userInfo = queryAppUserInfo(request.getConsumerId());
        Station station = enterpriseService.selectStationById(payOrder.getStationId());
        if(station == null){
            throw new CustomException("未查询到油站");
        }
        FleetCardSubVo cardSubVo = queryFleetCard(userInfo, Long.valueOf(station.getEnterpriseId()));
        if (cardSubVo == null) {
            throw new CustomException("车队卡不存在", 1001);
        }
        if(cardSubVo.getFleetCardId() == null
                || Objects.equals(cardSubVo.getSecondaryCardAllocationType(),FleetCard.USE_TYPE_SHARE)){
            // 主卡支付 或 子卡支付但是主卡余额共享
            FleetCard fleetCard = new FleetCard();
            //设置主卡id
            fleetCard.setId(cardSubVo.getFleetCardId()==null?cardSubVo.getId(): cardSubVo.getFleetCardId());
            fleetCard.setFleetName(cardSubVo.getFleetName());
            fleetCard.setBalance(cardSubVo.getBalance());
            fleetCard.setEnterpriseId(cardSubVo.getEnterpriseId());
            fleetCard.setPhone(cardSubVo.getPhone());
            fleetCardService.cdkPay(fleetCard,station,payOrder);
        }else{
            // 子卡支付
            fleetCardSubService.cdkSubPay(cardSubVo,station,payOrder);
        }
        payOrder.setStatus("1");
        payOrder.setPayDate(new Date());
        payOrderMapper.updateByPrimaryKeySelective(payOrder);
        gzhNewsTemplateService.feiePush(payOrder);
    }

    private PayOrderVO saveOrUpdatePayOrder(PayOrder originOrder,PayOrderRequest request){

        Station station = enterpriseService.selectStationById(request.getStationId());
        if(station == null){
            throw new CustomException("未查询到油站");
        }

        StaOilGun staOilGun = queryStaOilGun(request.getGunName(), request.getStationId());

        PayOrder payOrder = createNewPayOrder(request, station, staOilGun);
        if (originOrder != null) {
            payOrder.setOrderId(originOrder.getOrderId());
            payOrder.setOrderNo(originOrder.getOrderNo());
        }else{
            String ordNo = com.platform.qujia.utils.StringUtils.generateOrdNo();
            payOrder.setOrderNo(ordNo);                                          //订单号
        }

        AppUserInfo userInfo = queryAppUserInfo(request.getConsumerId());
        payOrder.setConsumer(userInfo.getBlogNickName());                   //昵称
        payOrder.setCustomerPhone(userInfo.getMobilePhone());
        int i = 0;
        if (payOrder.getOrderId() == null) {
            PayOrderHandle.setPayOrderInvoiceStatus(payOrder);
            i = payOrderMapper.insertSelective(payOrder);
        }
        if (i<0) {
            throw new CustomException("创建订单失败");
        }
        StoredCardVO cardVO = queryStoredCardVO(payOrder,userInfo,staOilGun.getOil().getCardType(),station);
        ReductionAndCouponDTO reductionAndCouponDTO = queryReductionAndCoupon(payOrder, request, userInfo, station,staOilGun);
        BigDecimal amt = MathUtil.subtract(BigDecimal.valueOf(payOrder.getAmt()),reductionAndCouponDTO.getReductionAmt());
        payOrder.setDiscountAmt(reductionAndCouponDTO.getReductionAmt().doubleValue());

        CouponUser couponUser = reductionAndCouponDTO.getCouponUser();
        if (couponUser != null) {
            BigDecimal disCouponAmt = couponUser.getCouponAmtByCNY();
            amt = amt.subtract(disCouponAmt);
            if (amt.compareTo(DecimalConstant.O_01)<0) {
                amt = DecimalConstant.O_01;
            }
            payOrder.setDiscountCouponAmt(disCouponAmt.doubleValue());
        }else{
            couponUser = new CouponUser();
            couponUser.setCouponNo(StringUtils.EMPTY);
            couponUser.setCouponAmt(BigDecimal.ZERO);
        }
        payOrder.setAmt(amt.doubleValue());
        i = payOrderMapper.updateByPrimaryKeySelective(payOrder);
        if (i<0) {
            throw new CustomException("更新订单失败");
        }
        PayOrderVO payOrderVO = new PayOrderVO();
        payOrderVO.setOrderNo(payOrder.getOrderNo());
        payOrderVO.setReceivableAmt(new BigDecimal(request.getReceivableAmt()));
        payOrderVO.setDiscountAmt(reductionAndCouponDTO.getReductionAmt());
        payOrderVO.setDiscountCouponAmt(couponUser.getCouponAmtByCNY());
        payOrderVO.setCouponNo(couponUser.getCouponNo());
        payOrderVO.setCouponUserId(couponUser.getCouponUserId());
        payOrderVO.setAmt(amt);
        payOrderVO.setOilLiters(new BigDecimal(payOrder.getOrderLiters()));
        payOrderVO.setStoredAmt(cardVO.getAmt());
        payOrderVO.setCouponList(reductionAndCouponDTO.getCouponUserList());
        payOrderVO.setStationName(station.getStationName());
        payOrderVO.setTotalDiscountAmt(MathUtil.add(payOrderVO.getDiscountAmt(),payOrderVO.getDiscountCouponAmt()));
        return payOrderVO;
    }

    private PayOrder createNewPayOrder(PayOrderRequest request,Station station,StaOilGun staOilGun){
        PayOrder newPayOrder = new PayOrder();             //生成订单参数
        newPayOrder.setEnterpriseId(station.getEnterpriseId());
        newPayOrder.setEnterpriseName(station.getEnterprise().getEnterpriseName());
        newPayOrder.setOrderRandomId(request.getOrderRandomId());
        newPayOrder.setAppType(request.getAppType());
        newPayOrder.setPayType(request.getPayType());
        newPayOrder.setOrderOriginType(request.getOrderOriginType());
        newPayOrder.setStationName(station.getStationName());
        newPayOrder.setUtmSource(request.getUtmSource());

//        newPayOrder.setConsumer(appUserInfo.getBlogNickName());                   //昵称
//        newPayOrder.setConsumerId(appUserInfo.getUserId());                       //用户id
//        newPayOrder.setCustomerPhone(appUserInfo.getMobilePhone());
        newPayOrder.setOilPersonnelId(request.getUserId());

        newPayOrder.setStationId(request.getStationId());                  //油站id
        newPayOrder.setStatus("0");                                                //创建订单 未支付状态 0
        newPayOrder.setCreatedDate(new Date());           //创建时间
        newPayOrder.setOilGun(request.getGunName());                        //油枪号
        newPayOrder.setOilPersonnelId(request.getOilPersonnel());  //加油员id
        newPayOrder.setReceivableAmt(Double.valueOf(request.getReceivableAmt()));      //订单应收金额
        newPayOrder.setDzkAmt(Double.valueOf(request.getReceivableAmt()));             //电子卡金额

        BigDecimal oilPrice = staOilGun.getOilStationPrice();
        BigDecimal oilLiters = new BigDecimal(request.getReceivableAmt()).divide(oilPrice, 4, RoundingMode.HALF_UP); //加油升数

        newPayOrder.setOilPirce(oilPrice.toString()); //油价 原价
        newPayOrder.setOrderType(staOilGun.getOil().getOilClass()); // 油品类
        newPayOrder.setOilName(staOilGun.getOilId().toString()); // 油品id
        newPayOrder.setAmt(Double.valueOf(request.getReceivableAmt())); //实收金额
        newPayOrder.setDiscountAmt(0d); //优惠金额
        newPayOrder.setDiscountCouponAmt(0d);//优惠卷金额
        newPayOrder.setOrderLiters(oilLiters.toString()); // 油升数
        newPayOrder.setCommission(0d);
        newPayOrder.setChannelFeePayer("1");
        newPayOrder.setServiceCharge(BigDecimal.ZERO);
        return newPayOrder;
    }

    private PayOrder queryNotPaidOrderByOrderNo(String orderNO){
        PayOrder payOrder = payOrderMapper.selectByOrdNo(orderNO);
        if (payOrder == null) {
            throw new CustomException(CodeMsg.NO_ORDER);
        }
        if (!StringUtils.equals("0",payOrder.getStatus())) {
            throw new CustomException(CodeMsg.SELECT_ORDER_ERROR);
        }
        return payOrder;
    }

    private StaOilGun queryStaOilGun(String gunName,Integer stationId){
        StaOilGun queryOilGun = new StaOilGun();
        queryOilGun.setGunName(gunName);   // 枪号
        queryOilGun.setStationId(stationId);
        StaOilGun staOilGun = enterpriseService.selectStaGunInfo(queryOilGun);
        if(staOilGun == null){
            throw new CustomException("未查到目标油枪");
        }
        return  staOilGun;
    }

    private AppUserInfo queryAppUserInfo(Integer consumerId){
//        AppUserInfo form = new AppUserInfo();
//        form.setMobilePhone(mobilePhone);
//        form.setStationId(enterpriseId);
//        AppUserInfo appUserInfo = appUserInfoService.getAppUserInfo(form);
        AppUserInfo appUserInfo = appUserInfoService.getById(consumerId);
        if(appUserInfo == null){
            throw new CustomException("查无用户");
        }
        return appUserInfo;
    }

    private CustomerElectronicCard queryElectronicCard(AppUserInfo appUserInfo,String oilType,Station station){
        CustomerElectronicCard customerElectronicCard = electronicMembershipCardService.getCustomerElectronicCard(appUserInfo, oilType, station);
//        if (customerElectronicCard == null) {
//            throw new CustomException("电子卡未找到");
//        }
        return customerElectronicCard;
    }

    /**
     *
     * @param appUserInfo
     * @param enterpriseId
     * @return 返回主卡或子卡，当设置共享主卡额度或会员关联的的是主卡balance为主卡的余额，id是主卡或子卡的主键id，只有子卡fleetCardId字段不为空
     */
    private FleetCardSubVo queryFleetCard(AppUserInfo appUserInfo,Long enterpriseId){
        FleetCardSub cardSub = new FleetCardSub();
        cardSub.setAppUserId(Long.valueOf(appUserInfo.getUserId()));
        cardSub.setEnterpriseId(enterpriseId);
        FleetCardSub one = fleetCardSubMapper.getOne(cardSub);
        FleetCardSubVo cardSubVo = new FleetCardSubVo();
        FleetCard card;
        if (one != null) {
            // 手机号关联的是子卡
            card = fleetCardMapper.selectById(one.getFleetCardId());
            if (!Objects.equals(one.getStatus(), FleetCardSub.REVIEW_PASS) || card == null) {
                //throw new CustomException("车队卡不存在", 1001);
                return null;
            }
            Integer secondaryCardAllocationType = card.getSecondaryCardAllocationType();
            if(Objects.equals(secondaryCardAllocationType, FleetCard.USE_TYPE_SHARE)){
                // 共享主卡额度，返回主卡额度
                one.setBalance(card.getBalance());
            }
            cardSubVo.setId(one.getId());
            cardSubVo.setFleetName(card.getFleetName());
            cardSubVo.setPhone(appUserInfo.getMobilePhone());
            cardSubVo.setEnterpriseId(one.getEnterpriseId());
            cardSubVo.setFleetCardId(card.getId());
            cardSubVo.setCardNumber(one.getCardNumber());
            cardSubVo.setBalance(one.getBalance());
            cardSubVo.setStatus(2);
            cardSubVo.setSecondaryCardAllocationType(secondaryCardAllocationType);
//            if(Objects.equals(secondaryCardAllocationType,FleetCard.USE_TYPE_ALLOCATION)){
//                // 手动分配子卡额度，返回子卡额度
//                card.setBalance(one.getBalance());
//            }
        }else{
            // 手机号关联的是主卡
            FleetCard fleetCard = new FleetCard();
            fleetCard.setPhone(appUserInfo.getMobilePhone());
            fleetCard.setEnterpriseId(enterpriseId);
            card = fleetCardMapper.getOne(fleetCard);
            if (card == null) {
                //throw new CustomException("车队卡不存在", 1001);
                return null;
            }
            cardSubVo.setId(card.getId());
            cardSubVo.setFleetName(card.getFleetName());
            cardSubVo.setPhone(card.getPhone());
            cardSubVo.setEnterpriseId(card.getEnterpriseId());
            cardSubVo.setCardNumber(card.getCardNumber());
            cardSubVo.setBalance(card.getBalance());
            cardSubVo.setStatus(2);
            cardSubVo.setSecondaryCardAllocationType(card.getSecondaryCardAllocationType());
        }
        return cardSubVo;
    }

    private StoredCardVO queryStoredCardVO(PayOrder payOrder,AppUserInfo userInfo,String oilType,Station station){
        PayTypeEnum typeEnum = PayTypeEnum.getByType(payOrder.getPayType());
        StoredCardVO cardVO = new StoredCardVO();
        switch (typeEnum){
            case dzk:
                payOrder.setConsumerId(userInfo.getUserId());
                payOrder.setCdkType(StringUtils.EMPTY);
                CustomerElectronicCard card = queryElectronicCard(userInfo, oilType, station);
                cardVO.setAmt(card == null ? BigDecimal.ZERO : card.getTotalAmt());
                cardVO.setStoredCardType("dzk");
                break;
            case cdk:
                FleetCardSubVo card1 = queryFleetCard(userInfo, Long.valueOf(station.getEnterpriseId()));
//                if (card1 == null) {
//                    throw new CustomException("车队卡不存在", 1001);
//                }
                if (card1 != null) {
                    payOrder.setConsumerId(Math.toIntExact(card1.getId()));
                    cardVO.setAmt(card1.getBalance());
                }else{
                    cardVO.setAmt(BigDecimal.ZERO);
                }
                cardVO.setStoredCardType("cdk");
                break;
            default:
                throw new CustomException("不支持该支付方式");
        }
        return cardVO;
    }

    /**
     * 查询立减优惠金额和优惠卷
     * @param payOrder
     * @param request
     * @param userInfo
     * @param station
     */
    private ReductionAndCouponDTO queryReductionAndCoupon(PayOrder payOrder, PayOrderRequest request, AppUserInfo userInfo, Station station,StaOilGun staOilGun){
        ReductionAndCouponDTO reductionAndCouponDTO = ReductionAndCouponDTO.newEmptyInstance();
        if (StringUtils.equals(PayTypeEnum.cdk.getType(),request.getPayType())) {
            //车队卡不计算优惠
            return reductionAndCouponDTO;
        }
        request.setCardFlag("2"); //设置电子表示
        request.setOilId(staOilGun.getOil().getOilId()); // 设置oilId
        payOrder.setOilId(staOilGun.getOil().getOilId()); // 设置oilId
        if (!request.getEnableCoupon()) {
            request.setCouponNo(null);
            request.setCouponUserId(null);
        }
        if (StringUtils.isNotBlank(request.getCouponNo()) && StringUtils.isNotBlank(request.getCouponUserId())) {
            // 设置手动选取的优惠卷
            payOrder.setCouponUserId(request.getCouponUserId());
        }
        BigDecimal reductionAmount = BigDecimal.ZERO;
        request.setMobilePhone(userInfo.getMobilePhone());
        Map<String, Object> a= payOrderService.cherkCouponCount(request);
        if(a.get("status").equals("2")){
            String msg = a.get("msg").toString();
            throw new CustomException(msg);
        }
        //计算优惠金额
        Map<String,Object> amountMap = reductionActivityService.selectReductionByPayOrderCoupon(userInfo, payOrder, "CSP", request, station,staOilGun);
        Map<String, Object> rCHResult = reductionActivityService.getRCHReductionAmt(userInfo,payOrder,request,station);
        BigDecimal rCHReductionAmt = (BigDecimal) rCHResult.get("rCHReductionAmt");
        List<CouponUser> couponList2 = (List<CouponUser>) rCHResult.get("couponList");

        //记录 充值立减活动优惠金额、消费立减活动优惠金额
        if(amountMap.get("reductionAmount")!=null){
            payOrder.setConsumeDiscountAmt(new BigDecimal(amountMap.get("reductionAmount").toString()));
        }
        if(rCHResult.get("rCHReductionAmt")!=null){
            payOrder.setRechargeDiscountAmt((BigDecimal) rCHResult.get("rCHReductionAmt"));
        }

        reductionAmount=reductionAmount.add(rCHReductionAmt);

        if(amountMap != null && amountMap.containsKey("reductionAmount") && amountMap.get("reductionAmount") != null){

            reductionAmount = reductionAmount.add(new BigDecimal(amountMap.get("reductionAmount").toString()));
            // 每笔订单最低付款额度0.01
            BigDecimal amt = new BigDecimal(request.getReceivableAmt());
            if((amt.subtract(reductionAmount)).compareTo(DecimalConstant.O_01)<=0){
                reductionAmount = amt.subtract(DecimalConstant.O_01);
            }
        }

        if(amountMap != null && amountMap.containsKey("activityId") && amountMap.get("activityId") != null){
            payOrder.setActivityId(Long.valueOf(amountMap.get("activityId").toString()));
        }
        //  拉取标签信息，将标签信息添加到对应的订单之中
        if(amountMap != null && amountMap.containsKey("labelId") && amountMap.get("labelId") != null){
            payOrder.setLabelId(Integer.valueOf(amountMap.get("labelId").toString()));
        }
        if(amountMap != null && amountMap.containsKey("labelName") && amountMap.get("labelName") != null){
            payOrder.setLabelName(amountMap.get("labelName").toString());
        }
        //可用的优惠券列表
        BigDecimal amt = new BigDecimal(request.getReceivableAmt()).subtract(reductionAndCouponDTO.getReductionAmt());
        if(amountMap != null && amountMap.containsKey("couponList") && amountMap.get("couponList") != null){
            List<CouponUser> couponList = (List<CouponUser>) amountMap.get("couponList");
            Set<CouponUser> quchong=new HashSet<>();
            quchong.addAll(couponList);
            quchong.addAll(couponList2);
            List<CouponUser> total=new ArrayList<>(quchong);
            // 计算每张优惠卷实际优惠的金额，根据优惠卷实际优惠的金额倒序排序,
            // todo 应付减去立减优惠后再计算优惠卷金额
            for (CouponUser user : total) {
                if(user.getCouponType().equals("1")){
                    //现金
                    user.setCouponAmtByCNY(user.getCouponAmt());
                }else if(user.getCouponType().equals("2")){
                    //折扣 应付*couponAmt*0.01
                    user.setCouponAmtByCNY(amt.multiply(user.getCouponAmt()).multiply(DecimalConstant.O_01).setScale(2,RoundingMode.DOWN));
                }
//                    if(user.getNewAmtByCoupon().compareTo(new BigDecimal("0.01"))<=0){
//                        user.setNewAmtByCoupon(new BigDecimal("0.01"));
//                    }
            }
            total.sort((c1,c2) -> c2.getCouponAmtByCNY().compareTo(c1.getCouponAmtByCNY()));
            reductionAndCouponDTO.setCouponUserList(total);
            //resultMap.put("couponList", total);
        }

        // 判断享受的立减优惠是否与优惠卷互斥
        boolean couponNotExclusion = false; //享受的立减活动与优惠劵不互斥标识

        Object r1 = amountMap.get("activityRule");
        Object r2 = rCHResult.get("activityRule");

        //两个立减活动都不可使用优惠劵

//            couponNotExclusion = r1 == null; // r1== null 可用优惠卷
//            couponNotExclusion = couponNotExclusion || StringUtils.equals("1",(String)r1); // r1 == 1 可用优惠卷
//
//            couponNotExclusion = couponNotExclusion || (r2 == null);
//            couponNotExclusion = couponNotExclusion || StringUtils.equals("1",(String)r2);
//
//            if (!couponNotExclusion) {
//                return reductionAndCouponDTO;
//            }


        if(r1 == null && r2 == null){
            couponNotExclusion = true;
        }else if(r1 == null && StringUtils.equals("1", (String) r2)){
            couponNotExclusion = true;
        }else if(r2 == null && StringUtils.equals("1",(String)r1)){
            couponNotExclusion = true;
        }else if(StringUtils.equals("1",(String)r1) || StringUtils.equals("1",(String)r2)){
            couponNotExclusion = true;
        }

        if (request.getEnableDiscount()) {
            // 立减优惠打开
            reductionAndCouponDTO.setReductionAmt(reductionAmount);
        }else{
            // 立减优惠关闭，设置不互斥
            couponNotExclusion = true;
        }

        if (request.getEnableCoupon()) {
            // 优惠卷开关打开

//            if (!couponNotExclusion) {
//                return reductionAndCouponDTO;
//            }

            //不互斥选择优惠劵

            List<CouponUser> couponUserList = reductionAndCouponDTO.getCouponUserList();
            if (StringUtils.isNotBlank(request.getCouponNo())) {
                //手动选择优惠卷
                String couponNo = request.getCouponNo();
                Optional<CouponUser> first = couponUserList.stream().filter(c -> StringUtils.equals(c.getCouponNo(),couponNo)).findFirst();
                if (first.isPresent()) {
                    //优惠劵找到
                    reductionAndCouponDTO.setCouponUser(first.get());
                    if (!couponNotExclusion) {
                        // 立减活动优惠劵互斥，设置立减优惠金额0
                        reductionAndCouponDTO.setReductionAmt(BigDecimal.ZERO);
                    }
                }
//                if (first.isPresent()) {
//                    reductionAndCouponDTO.setCouponUser(first.get());
//                }else{
//                    throw new CustomException("优惠卷不存在");
//                }
            }else{
                // 没有手动选择，选择优惠力度最大的，但是不能超过应付金额
                if (couponNotExclusion) {
                    // 立减与优惠劵不互斥才选择最大的
                    Optional<CouponUser> first = couponUserList.stream().filter(c -> c.getCouponAmtByCNY().compareTo(amt) <= 0).findFirst();
                    first.ifPresent(reductionAndCouponDTO::setCouponUser);
                }
            }
        }

        //resultMap.put("couponEnabledFlag", station.getEnterprise().getCouponEnabledFlag());

        //油企是否开启优惠券功能
//        if(null != station.getEnterprise().getCouponEnabledFlag() && "1".equals(station.getEnterprise().getCouponEnabledFlag())){
//            Map<String,Object> p = new HashMap<>();
//            p.put("issueType", "3");
//            p.put("stationId", station.getStationId());
//            p.put("curTime", new Date());
//            //获取油企给当前油站设置的issueType=3时，消费完成后的可选择领取的优惠券活动;
//            List<CouponIssue> couponIssueInfo = couponService.selectCouponListByCouponIssueId(p);
//            if(null !=couponIssueInfo && couponIssueInfo.size() >=1){
//                resultMap.put("couponIssueInfo", couponIssueInfo.get(0).getCouponIssueId());
//            }
//        }

        return reductionAndCouponDTO;
    }

}
